package tij4.concurrent.source;

import java.util.concurrent.*;

class CircularSet {
    private int[] array;
    private int len;
    private int index = 0;

    //参数初始化并且把数组都初始化为-1
    public CircularSet(int size) {
        this.array = new int[size];
        len = size;
        for (int i = 0; i < size; i++) {
            array[i] = -1;
        }
    }
    //赋值，并把index的值 +1
    public synchronized void add(int i) {
        array[index] = i;
        index = ++index % len;
    }
    //检查传入的val是否在包含在array数组中
    public synchronized boolean contains(int val) {
        for (int i = 0; i < len; i++) {
            if(array[i] == val){
                return true;
            }
        }
        return false;
    }
}

public class SerialNumberChecker {
    private static final int SIZE = 10;
    private static CircularSet circularSet = new CircularSet(100000);
    private static ExecutorService executorService = Executors.newCachedThreadPool();

    static class SerialCheck implements Runnable {
        @Override
        public void run() {
            int nextSerialNumber = SerialNumberGenerator.nextSerialNumber();
            if(circularSet.contains(nextSerialNumber)) {
                System.out.println("Duplicate: " + nextSerialNumber);
                System.exit(0);
            }
            circularSet.add(nextSerialNumber);
        }
    }

    public static void main(String[] args) throws Exception {
        for (int i = 0; i < SIZE; i++) {
            executorService.execute(new SerialCheck());
            if (args.length > 0) {
                TimeUnit.SECONDS.sleep(new Integer(args[0]));
                System.out.println("No duplicates detected");
                System.exit(0);
            }
        }

    }
}
